<?php
namespace App\Console\Commands\Env;

use Symfony\Component\Console\Attribute\AsCommand;
use Jammiest\SwigeCore\Console\Commands\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'env:validate',
    description: '验证环境变量配置'
)]
class ValidateCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('验证环境变量');

        try {
            $requiredVars = [
                'APP_NAME',
                'APP_ENV',
                'APP_KEY',
                'DB_HOST',
                'DB_DATABASE'
            ];

            $missingVars = [];
            foreach ($requiredVars as $var) {
                if (!isset($_ENV[$var]) || empty($_ENV[$var])) {
                    $missingVars[] = $var;
                }
            }

            if (!empty($missingVars)) {
                throw new \RuntimeException(
                    "缺少必需环境变量: \n" . implode("\n", $missingVars)
                );
            }

            // 检查APP_KEY格式
            if (!isset($_ENV['APP_KEY']) || !str_starts_with($_ENV['APP_KEY'], 'base64:')) {
                throw new \RuntimeException('APP_KEY 格式不正确，应以 base64: 开头');
            }

            $io->success('所有必需环境变量已正确配置');
            return Command::SUCCESS;

        } catch (\Exception $e) {
            $io->error($e->getMessage());
            return Command::FAILURE;
        }
    }
}